function [ binmask_new,merged ] = merging_correlation( stack,binmask,corrthres )
%UNTITLED Summary of this function goes here
% Merging of rois by cross correlation   Detailed explanation goes here

%% preparation

corr_thresh = .8;

%calculate masksize for each mask
n_segs = size(binmask,3);
seg_size = zeros(1,n_segs);

n_frames = size(stack,3);

for ii=1:n_segs
    seg_size(ii) = nnz(binmask(:,:,ii));
end

%calculate average trace for each mask (sum over all pixels / area)
averageTraces=zeros(n_frames,n_segs);
     for nsl=1:n_frames
         for j=1:n_segs
             p=stack(:,:,nsl);
             averageTraces(nsl,j)=sum(p(binmask(:,:,j)));
         end
     end
     
     for j=1:n_segs
         averageTraces(:,j)=averageTraces(:,j)/seg_size(j);
     end

%% merging
%right now we are only merging once to create new segments. One could also
%go on and calculate the correlation of the merged segments with other
%segments

still_merging =1;
while still_merging == 1
    still_merging = 0;
    corrMat=corr(averageTraces);
    n_redsegs=n_segs;
    merged = zeros(n_redsegs);
     for n=1:n_redsegs-1
         for m=n+1:n_redsegs
             if corrMat(n,m)>corrthres
                 merged(n,m)=1;
             end
         end
        
     end
    binmask_new = binmask;
    %this way we are merging by segment order. 
    for nn=n_redsegs-1:-1:1
        
        merged_to = find(merged(nn,:));
        for ii=1:numel(merged_to)
            i_to_merge = merged_to(ii);
            binmask_new(:,:,nn) = binmask_new(:,:,nn) | binmask_new(:,:,i_to_merge);
            binmask_new(:,:,i_to_merge) = false(size(binmask,1),size(binmask,2));
        end
        
    end
end
outsegs = squeeze(sum(sum(binmask_new)))>0; %this way we find the indices of the segments still containing pixel
binmask_new = binmask_new(:,:,outsegs);


end

